// 模板
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
const state = {
  carts: JSON.parse(localStorage.getItem('carts') || '[]').filter((item) => {
    return item.email == sessionStorage.getItem('email');
  }),
  curpdt: [],
};

const mutations = {
  add(state, obj) {
    if (sessionStorage.getItem('email') == undefined) {
      console.log('iiiiiii');
      Toast({
        message: '请先登陆后在加购商品',
        position: 'bottom',
      });
      return;
    }
    console.log(111);
    var index = state.carts.findIndex((item) => {
      return item.id == obj.id;
    });
    if (index == -1) {
      state.carts.push(obj);
    } else {
      state.carts[index].count += obj.count;
    }
    console.log(state.carts);
    localStorage.setItem('carts', JSON.stringify(state.carts));
    Toast({
      message: '添加购物车成功',
      position: 'bottom',
    });
  },
  pay(state, obj) {
    state.curpdt = [];
    var flag = obj instanceof Array;
    if (flag) {
      state.curpdt = obj;
    } else {
      obj.count = 1;
      state.curpdt.push(obj);
    }
  },
  remove(state, id) {
    state.carts = state.carts.filter((item) => {
      return item.id != id;
    });
    localStorage.setItem('carts', JSON.stringify(state.carts));
  },
};

const actions = {};

const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
